import Vue from 'vue'
import VueI18n from 'vue-i18n'
import storage from 'store'
import moment from 'moment'
import languageConfig from './lang/common'

// default lang
// import enUS from './lang/en-US'
import enUS from './lang/common'

Vue.use(VueI18n)

export const defaultLang = 'en-US'

const messages = {
  'en-US': {
    ...enUS
  }
}

const i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: defaultLang,
  fallbackLocale: defaultLang,
  messages
})

const loadedLanguages = [defaultLang]

function setI18nLanguage (lang) {
  i18n.locale = lang
  // request.headers['Accept-Language'] = lang
  document.querySelector('html').setAttribute('lang', lang)
  return lang
}

export function loadLanguageAsync (lang = defaultLang, res) {
  return new Promise(resolve => {
    // 本地缓存语言设置
    storage.set('lang', lang)
    let tempMsg = languageConfig(res)
    const locale = tempMsg
    i18n.setLocaleMessage(lang, locale)
    loadedLanguages.push(lang)
    moment.updateLocale(locale.momentName, locale.momentLocale)
    return setI18nLanguage(lang)
  })
}

export function i18nRender (key) {
  return i18n.t(`${key}`)
}



export default i18n
